package com.song.demo.webmvc.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 使用JDK proxy API生成代理类
 */
public class GPJdkDynamicAopProxy implements GPAopProxy, InvocationHandler {

    private GPAdvisedSupport advisedSupport;


    public GPJdkDynamicAopProxy(GPAdvisedSupport advisedSupport){
        this.advisedSupport = advisedSupport;
    }

    @Override
    public Object getProxy() {
        return getProxy(this.advisedSupport.getTargetClass().getClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        //JDK生成代理核心方法
       return Proxy.newProxyInstance(classLoader,this.advisedSupport.getTargetClass().getInterfaces(),this);
    }

    //invoke()方法是执行代理的关键入口
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //将每一个JoinPoint也就是被代理的业务方法封装成一个拦截器，组成一个拦截器链
        List<Object> methods = advisedSupport.getInterceptorsAndDynamicInterceptionAdvice(method, this.advisedSupport.getTargetClass());
        //交给拦截器链MethodInvocation的proceed()方法执行
        GPMethodInvocation invocation = new GPMethodInvocation(proxy,this.advisedSupport.getTarget(),method,args,this.advisedSupport.getTargetClass(),methods);


        return invocation.proceed();
    }
}
